package com.fansl.allround.common.security.handler;

import cn.hutool.core.util.CharsetUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.fansl.allround.common.core.constant.CommonConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author fansl
 * @Description: 认证失败处理
 * @date 2019/9/27 18:30
 */
@Slf4j
@AllArgsConstructor
public class AbstractAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private ObjectMapper objectMapper;
    /**
     * 认证失败
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        log.error("认证失败,error:{}",exception.getMessage(),exception);
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(CommonConstants.CONTENT_TYPE);
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(R.failed(exception.getMessage())));
    }
}
